import React, { useEffect, useState } from 'react';
import { Button, Card, Col, Descriptions, Modal, Row, Steps, Tabs, Tag } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { ProCard, ProFormUploadButton, ProTable } from '@ant-design/pro-components';
import { FileTextOutlined, UnorderedListOutlined } from '@ant-design/icons';
import ActivityForm from '@/pages/activityInfo/activityDetails/activityForm';
import { Pie } from '@ant-design/plots';
import { Calendar } from 'antd';
import { ProColumns } from '@ant-design/pro-components';
import { connect, history } from 'umi';
import { useLocation } from 'umi';
import {
  getdetail,
  getRegister,
  getStuJoinList,
  getSubActivityList,
  getActivityStatus, checkInStatus
} from '@/services/activityInfo';
import { Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { message, Upload } from 'antd';
import { Link } from '_umi@3.5.41@umi';
export type TableListItem = {
  key: number;
  stuName: string;
  stuCode: string;
  majorLabel: string;
  classLabel: string;
  isJoin: string
};
export type Status = {
  color: string;
  text: string;
};
const { Dragger } = Upload;
const countStyle = {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  textAlign: 'justify',
  color: 'white',
  fontSize: '30px',
  fontWeight: 'bold',
};
const statusMap = [
  {
    color: 'green',
    text: '已打卡',
  },
  {
    color: 'red',
    text: '未打卡',
  },
];
const stuJoinListColumns: ProColumns<TableListItem>[] = [
  {
    title: '姓名',
    width: 200,
    align: 'left',
    dataIndex: 'stuName',
    render: (text, record) => {
      return <a>{text}</a>
    }
  },
  {
    title: '学号',
    width: 200,
    align: 'left',
    dataIndex: 'stuCode',
  },
  {
    title: '专业',
    width: 200,
    align: 'left',
    dataIndex: 'majorLabel',
  },
  {
    title: '班级',
    width: 200,
    dataIndex: 'classLabel',
  },
  {
    title: '是否打卡',
    width: 200,
    dataIndex: 'status',
    render: (_, record) => <Tag color={record.status?.color}>{record.status?.text}</Tag>,
  },
];
const subActivityTableColumns: ColumnsType<any> = [
  {
    title: '活动名称',
    dataIndex: 'activityLabel',
    key: 'activityLabel',
    width: '20%',
    render: (text, record: any) => {
      // 如果不是教师
      if (localStorage.getItem("roleId") != '2') {
        return (
          <a
            onClick={() => {
              history.push(`/activityInfo/activityDetails?activityId=${record.id}`)
              window.location.reload()
            }}>
            {text}
          </a>
        )
      } else {
        return (
          <a
            onClick={() => {
              history.push(`/activityInfoTeacher/activityDetails?activityId=${record.id}`)
              window.location.reload()
            }}>
            {text}
          </a>
        )
      }
    }
  },
  {
    title: '举办方',
    dataIndex: 'organizationalUnit',
    key: 'organizationalUnit',
    width: '20%',
  },
  {
    title: '举办地点',
    dataIndex: 'activityAddress',
    key: 'activityAddress',
    width: '20%',
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: '20%',
    render: (startTime: string) => {
      const date = new Date(startTime);
      return date.toLocaleString(); // 使用toLocaleString()方法将时间格式化为本地日期时间字符串
    },
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    width: '20%',
    render: (endTime: string) => {
      const date = new Date(endTime);
      return date.toLocaleString(); // 使用toLocaleString()方法将时间格式化为本地日期时间字符串
    },
  },
];
const props: UploadProps = {
  name: 'file',
  multiple: true,
  action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  onChange(info) {
    const { status } = info.file;
    if (status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      message.success(`${info.file.name} file uploaded successfully.`);
    } else if (status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
  onDrop(e) {
    console.log('Dropped files', e.dataTransfer.files);
  },
};
const ActivityDetails: React.FC = (props: any) => {
  let AttendanceYes = 0;
  const [Yes, setYes] = useState(0);
  const [No, setNo] = useState(0);
  let AttendanceNo = 0;
  const { Step } = Steps;
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const activityId = queryParams.get('activityId');
  const data = [
    {
      type: '未打卡',
      value: No,
    },
    {
      type: '已打卡',
      value: Yes,
    }
  ];
  const config = {
    appendPadding: 0,
    data,
    angleField: 'value',
    colorField: 'type',
    radius: 1,
    innerRadius: 0.6,
    label: {
      type: 'inner',
      offset: '-50%',
      content: '{value}',
      style: {
        textAlign: 'center',
        fontSize: 14,
      },
    },
    interactions: [
      {
        type: 'element-selected',
      },
      {
        type: 'element-active',
      },
    ],
    statistic: {

    },
  };
  const [subActivityTableData, setSubActivityTableData] = useState<any[]>();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [checkInResult, setcheckInResult] = useState();
  const [stuJoinList, setStuJoinList] = useState<any>();
  const [activityDetails, setActivityDetails] = useState();
  const [progressBarNum, setProgressBarNum] = useState(2);
  const [isMessageOpen, setIsMessageOpen] = useState(false);
  const [upLoadValue, setUpLoadValue] = useState(null)
  const [activityStatus, setActivityStatus] = useState("报名")
  const subActivityTableColumns: ColumnsType<any> = [
    {
      title: '活动名称',
      dataIndex: 'activityLabel',
      key: 'activityLabel',
      width: '20%',
      render: (text, record: any)=>{
        return <a onClick={()=>{
          if (activityStatus === "通过审核"){//如果已报名
            window.location.replace("/activityInfo/activityDetails?activityId="+record.id)
          }else {
            message.warn("请先通过父类活动的报名审核！")
          }
        }
        }>{text}</a>

      }
    },
    {
      title: '举办方',
      dataIndex: 'organizationalUnit',
      key: 'organizationalUnit',
      width: '20%',
    },
    {
      title: '举办地点',
      dataIndex: 'activityAddress',
      key: 'activityAddress',
      width: '20%',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: '20%',
      render: (startTime: string) => {
        const date = new Date(startTime);
        return date.toLocaleString(); // 使用toLocaleString()方法将时间格式化为本地日期时间字符串
      },
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: '20%',
      render: (endTime: string) => {
        const date = new Date(endTime);
        return date.toLocaleString(); // 使用toLocaleString()方法将时间格式化为本地日期时间字符串
      },
    },
  ];
  /*
  数据处理
  --------------------------------------------------------------------------------------------------
   */
  // 处理进度条
  const progressBar = (value: any) => {
    if (value) {
      const registrationDeadline = new Date(value.registrationDeadline)
      const startTime = new Date(value.startTime)
      const endTime = new Date(value.endTime)
      const currentTime = new Date()
      if (currentTime > registrationDeadline) setProgressBarNum(3)
      else if (currentTime > endTime) setProgressBarNum(4)
    }
  }
  const showMessage = () => {
    setIsMessageOpen(true);
  };
  const MessageOk = () => {
    setIsMessageOpen(false);
    console.log(upLoadValue)
    console.log(upLoadValue.file)
    console.log(upLoadValue.fileList[0])
    if (upLoadValue != null) {
      if (props.dispatch) {
        props.dispatch({
          //路径：model的namespace+effects函数名
          type: 'Model_Counsellor/takePartInEffects',
          payload: {
            upload: upLoadValue.fileList[0]?upLoadValue.fileList[0].originFileObj:null,
            activityId: activityId
          },
        });
      }
    }
  };
  const MessageCancel = () => {
    setIsMessageOpen(false);
  };
  /*
  --------------------------------------------------------------------------------------------------
  数据处理
 */

  /*
  数据请求
  --------------------------------------------------------------------------------------------------
   */
  useEffect(() => {
    console.log(activityId)
    checkInStatus({ stuCode: localStorage.getItem('userAccount'), activityId: activityId })
      .then((response: any) => {
        if (response.result === '0' || response.result === 0) {
          setcheckInResult(<Tag color="error">未打卡</Tag>);
        } else {
          setcheckInResult(<Tag color="warning">已打卡</Tag>);
        }
      })
      .catch((error) => {
      })
      .finally(() => {
      });
    getdetail(activityId).then((response: any) => {//活动详情
      console.log(response.result)
      setActivityDetails(response.result)
      progressBar(response.result)
    })
    getSubActivityList(activityId).then((response: any) => {//活动计划
      setSubActivityTableData(response.result)
    })
    getStuJoinList(activityId).then((response: any) => {//活动反馈
      response.result.forEach(item => {
        if (item.isAttendance === '1' || item.isAttendance === 1) {
          item.status = statusMap[1]
          AttendanceNo++
        } else {
          AttendanceYes++
          item.status = statusMap[0]
        }
      })
      setStuJoinList(response.result)
      setYes(AttendanceYes)
      setNo(AttendanceNo)
    })
    let data = {
      stuNumber: localStorage.getItem('userAccount'),
      activityId: activityId,
    }
    getActivityStatus(data).then((response: any) => {
      console.log(response)
      if (response.result == 1) setActivityStatus("已报名")
      else if (response.result == 2) setActivityStatus("通过审核")
      else setActivityStatus("报名")
    })
  }, []);
  /*
  --------------------------------------------------------------------------------------------------
  数据请求
   */
  return (
    <PageContainer>
      <Modal open={isMessageOpen} onOk={MessageOk} onCancel={MessageCancel} width={700}>
        <Card title="请上传报名表" bordered={false} style={{ width: "100%" }}>
          <Dragger beforeUpload={()=>(false)} {...props} onChange={setUpLoadValue} maxCount={1}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">单击或拖动文件到此区域以上传</p>
            <p className="ant-upload-hint">
              仅支持上传单个文件
            </p>
          </Dragger>
        </Card>
      </Modal>
      <Modal title="打卡情况" width={"50%"} open={isModalOpen} footer={null} onCancel={() => setIsModalOpen(false)}>
        <ProTable<TableListItem>
          columns={stuJoinListColumns}
          dataSource={stuJoinList}
          pagination={{ pageSize: 10 }}
          size={'small'}
          search={false}
          rowKey="key"
        />
      </Modal>
      <ProCard style={{ marginBottom: 24 }}>
        <Descriptions title={<div><span>活动进度</span>&nbsp;&nbsp;<span>{checkInResult}</span></div>}>
        </Descriptions>
        {/** 活动当天为活动进行中 **/}
        <Steps progressDot current={progressBarNum}>
          <Step title={<span style={{ fontSize: 14 }}>活动策划</span>} />
          <Step title={<span style={{ fontSize: 14 }}>发布活动</span>} />
          <Step title={<span style={{ fontSize: 14 }}>报名中</span>} />
          <Step title={<span style={{ fontSize: 14 }}>进行中</span>} />
          <Step title={<span style={{ fontSize: 14 }}>圆满结束！</span>} />
        </Steps>
      </ProCard>
      <Row gutter={24}>
        <Col xl={18} lg={24} md={24} sm={24} xs={24} >
          <Card title={<span style={{ marginBottom: 24 }}> <FileTextOutlined /> <b>活动详情</b> </span>}>
            <ActivityForm activityId={activityId} />
          </Card>
          <Card title={<span > <UnorderedListOutlined /> <b>活动计划</b> </span>}>
            <Table
              columns={subActivityTableColumns}
              rowKey="id"
              dataSource={subActivityTableData}
            />
          </Card>
        </Col>
        <Col xl={6} lg={24} md={24} sm={24} xs={24}>
          <Card bodyStyle={{ padding: 0 }} style={{ marginBottom: 24 }}>
            <Button style={{ width: "100%", height: 96 }} type="primary" size='large' onClick={showMessage} hidden={activityDetails?(activityDetails.parentsId?true:false):false}>
              <div style={countStyle}>{activityStatus}</div>
            </Button>
          </Card>
          <Card style={{ marginBottom: 24 }}>
            <div style={{ width: "100%" }}>
              <Calendar fullscreen={false} />
            </div>
          </Card>
          <Card style={{ marginBottom: 24, height: '350px' }} title="打卡情况" extra={<a onClick={() => setIsModalOpen(true)}>详情</a>}>
            <Pie {...config} padding={[0, 50, 250, 10]} />
          </Card>
        </Col>
      </Row>
    </PageContainer >
  );
};

export default connect(({ Model_Counsellor }: any) => ({
  Model_Counsellor,
}))(ActivityDetails);
